<?php
namespace app\middleware\api;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

use Tinywan\Jwt\JwtToken;
use Tinywan\Jwt\Exception\JwtTokenExpiredException;

class AuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {

    	$controller = $request->controller;

    	$ignore = ['app\api\controller\AuthController', 'app\api\controller\PaymentController'];

    	if(!in_array($controller, $ignore))
    	{
    		try{
    			//$user_info = JwtToken::getUser(); //（1）查询数据库数据

    			$user_info = JwtToken::getExtend(); //（2）只解析token数据

	    		if(empty($user_info))
    			{
    				return returnJson(401,'身份验证失败，请重新登录');
    			}else{

    				$request->user_info = $user_info;
    			}
    		} catch (JwtTokenExpiredException $e){

                return returnJson(401,'身份验证已过期，请重新登录');

            } catch(\Exception $e) {

    			return returnJson(401,'身份验证失败，请重新登录');
    		}
    	}else{

            try {
                $user_info = JwtToken::getExtend(); //（2）只解析token数据
                if(!empty($user_info))
                {
                    $request->user_info = $user_info;
                }else{
                    $request->user_info = [];
                }
            }catch (\Exception $e)
            {
                $request->user_info = [];
            }
        }
        return $handler($request);
    }
}